package com.atguigu.flink.charkoer11;

import com.atguigu.flink.been.OrderEvent;
import com.atguigu.flink.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

public class ProjectOrderWatch {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.readTextFile("input/OrderLog.csv")
                .map(new MapFunction<String, OrderEvent>() {
                    @Override
                    public OrderEvent map(String value) throws Exception {
                        String[] line = value.split(",");
                        return new OrderEvent(
                                Long.valueOf(line[0]),
                                line[1],
                                line[2],
                                Long.valueOf(line[3]) * 1000
                        );
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                                    @Override
                                    public long extractTimestamp(OrderEvent element, long recordTimestamp) {
                                        return element.getEventTime();
                                    }
                                })
                )
                .keyBy(OrderEvent::getOrderId)
                .window(EventTimeSessionWindows.withGap(Time.minutes(45)))
                .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
                    private ValueState<OrderEvent> state;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        state = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("ll", OrderEvent.class));
                    }

                    @Override
                    public void process(Long key,
                                        Context ctx,
                                        Iterable<OrderEvent> elements,
                                        Collector<String> out) throws Exception {
                        List<OrderEvent> list = AtguiguUtil.tolist(elements);
                        if (list.size() != 2) {
                            OrderEvent orderEvent = list.get(0);
                            String eventType = orderEvent.getEventType();
                            if ("create".equals(eventType)) {
                                state.update(orderEvent);
                            } else {
                                OrderEvent value = state.value();
                                if (value == null) {
                                    out.collect("订单: " + key + " 只有pay, 没有create, 请检查系统是否有问题...");
                                } else {
                                    out.collect("订单: " + key + " 被超时支付, 请检查系统是否有问题...");
                                }
                            }
                        }
                    }
                }).print();


        env.execute();
    }
}
